package com.jilefojing.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.octo.captcha.service.multitype.MultiTypeCaptchaService;
import com.jilefojing.beans.data.enums.ResponseEnum;
import com.jilefojing.beans.data.response.base.ResponseData;
import com.jilefojing.beans.data.web.request.RegisterRequest;
import com.jilefojing.beans.exception.UserContextException;
import com.jilefojing.context.beans.vo.UserContext;
import com.jilefojing.service.IRegisterService;
import com.jilefojing.web.base.BaseWeb;

/**
 * 注册
 * 
 * @author jiangguoshun
 *
 */
@Controller
@RequestMapping("register")
public class RegisterWeb extends BaseWeb {
	@Autowired
	private MultiTypeCaptchaService captchaService;
	@Autowired
	private IRegisterService registerService;

	@RequestMapping("page.html")
	public String toPage() {
		UserContext userContext = null;
		try {
			userContext = super.getUserContext();
		} catch (UserContextException e) {
			// 可忽略
		}
		if (userContext != null) {
			return super.redirect("/");
		}

		return "web/register";
	}

	/**
	 * 注册
	 * 
	 * @return
	 */
	@RequestMapping("")
	public @ResponseBody ResponseData register(RegisterRequest registerRequest, HttpServletRequest request) {
		ResponseData responseData = new ResponseData();
		Boolean isResponseCorrect = captchaService.validateResponseForID(request.getSession().getId(), registerRequest.getValidataImg());
		if (!isResponseCorrect) {
			responseData.setResponseEnum(ResponseEnum.IMG_VALIDATA_ERROR);
			return responseData;
		}

		try {
			registerService.register(registerRequest);
		} catch (UserContextException e) {
			if (e.getResponse() != null) {
				responseData.setResponseEnum(e.getResponse());
			} else {
				responseData.setResponseEnum(ResponseEnum.UNKNOWN);
				responseData.setResponseMessage(e.getMessage());
			}
		}

		return responseData;
	}
}
